<template>
  <a-select v-model:value="FormDataSelect">
    <a-select-option value="TestFormData1">测试表单数据1</a-select-option>
    <a-select-option value="TestFormData2">测试表单数据2</a-select-option>
    <a-select-option value="TestFormData3">测试表单数据3</a-select-option>
  </a-select>

  <a-form class="FormView" :label-col="labelCol" v-if="FormData.BasicParam">
    <template v-for="item in FormConfig">
      <!-- StringToRule 将规则转换为 True/False 状态,用来控制表单组显示及隐藏 -->
      <template v-if="StringToRule(item.Rule, FormData)">
        <div class="title">{{ item.Label }}</div>
        <template v-for="child in item.children">
          <!-- GetFormItemRull 以业务规则判断表单项是否显示 -->
          <!-- GetFormItemByFormType 以值类型判断是否显示这个表单项 -->
          <FormItemVue :Item="child" :Value="FormData" v-if="
          GetFormItemRull(item.childRule, child.Key, FormData) &&
          GetFormItemByFormType(child.FormType, FormData.BasicParam.FormType)" @ChangeValue="ChangeValue" />
        </template>
      </template>
    </template>
    <a-form-item class="ButtonView">
      <a-button type="primary" style="margin-left:150px" @click="ShowFormData">提交</a-button>
    </a-form-item>
  </a-form>
  <a-modal v-model:visible="visible" title="测试数据结果">
    <code><pre>{{ Code }}</pre></code>
  </a-modal>
</template>
<script setup>
import { nextTick, onMounted, ref, watch } from 'vue';
import { GetFormData } from './Apis.js'
import FormItemVue from './FormItem.vue';
import { FormConfig, StringToRule, GetFormItemRull, GetFormItemByFormType } from './Config.js'

// 表单标签布局
const labelCol = ref({ style: { width: '150px', } });

// 表单数据
const FormData = ref({});
const FormDataSelect = ref('TestFormData1');


// 切换数据
onMounted(async () => {
  FormData.value = await GetFormData(FormDataSelect.value);
});
watch(FormDataSelect, (val) => {
  FormData.value = {};
  nextTick(async () => {
    FormData.value = await GetFormData(val);
  })
})


// 显示结果
const Code = ref('');
const visible = ref(false);
const ShowFormData = () => {
  Code.value = JSON.stringify(FormData.value, 1, '  ');
  visible.value = true
}

// 当值改变时，利用 Function 的字符串拼接，来找到指定的位置，
// 因为 FormData 为双向绑定对象，
// 利用 Vue 的机制来更新数据变化的状态

const ChangeValue = (val, Config) => {
  new Function("val", "FormData", "FormData.value." + Config.Key + " = val")(val, FormData);
}


</script>

<style scoped>
.ButtonView {
  margin-top: 20px;
}

.FormView {
  width: 500px;
}

.title {
  padding: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #434343;
}

:deep(.ant-form-item) {
  margin-bottom: 0px;
}
</style>
